package news.servlet;

import news.dao.CategoryDao;
import news.dao.NewsDao;
import news.pojo.Category;
import news.pojo.News;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/edit")
public class NewEditServlet extends BaseServlet{
    private NewsDao newsDao = new NewsDao();
    private CategoryDao categoryDao = new CategoryDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = getIntegerParam("id",0);
        News news = null;
        List<Category> categoryList = new ArrayList<>();
        try {
            news = newsDao.selectOne(id);
            categoryList = categoryDao.selectAll(); // 查询出所有的分类列表
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(news == null){
            throw new ServletException("没有查询到要修改的新闻");
        }
        req.setAttribute("news",news);
        req.setAttribute("categoryList",categoryList);
        showPage("news-edit");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        int id = getIntegerParam("id",0);

        try {
            News n = newsDao.selectOne(id);
            n.setTitle(title);
            n.setContent(content);
            newsDao.update(n);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
        resp.setContentType("text/html");
        resp.getWriter().println("保存成功,<br><a href='javascript:history.go(-2);'>确定并返回</a>");

    }
}
